<template>
  <PageWrapper title="巡护统计" dense contentFullHeight contentClass="flex">
    <div class="flex-auto mt-4">
      <div style="background-color: #151515" class="flex m-4 p-4 pb-0">
        <BasicForm @register="registerForm" @submit="handleSubmit" />
        <a-button type="primary" @click="handleSubmit">查询</a-button>
      </div>

      <div style="height: 480px; background-color: #151515" class="m-4">
        <h2 class="p-4">巡护次数统计图</h2>
        <div
          ref="chartRef"
          :style="{
            height: '600px',
            width: '100%',
            backgroundColor: '#151515',
          }"
        ></div>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, onMounted, Ref, ref } from 'vue';

  import { PageWrapper } from '/@/components/Page';
  import { getPatrolCount } from '/@/api/sys/user';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import moment from 'moment';
  import { useECharts } from '/@/hooks/web/useECharts';
  import { EChartsOption } from 'echarts';

  const chartOptions: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        lineStyle: {
          width: 1,
          color: '#019680',
        },
      },
    },
    grid: { left: 16, right: 16, top: 24, bottom: 16, containLabel: true },
    yAxis: {
      type: 'value',
      max: 8000,
      splitNumber: 4,
    },
    xAxis: {
      type: 'category',
      data: [],
    },

    series: [
      {
        data: [],

        type: 'bar',
      },
    ],
  };

  // import DeptTree from './DeptTree.vue';

  export default defineComponent({
    name: 'PStat',
    components: { PageWrapper, BasicForm },
    setup() {
      const [registerForm, { getFieldsValue, validate }] = useForm({
        layout: 'inline',
        labelWidth: 90,

        fieldMapToTime: [['datetime', ['start_time', 'end_time'], 'X']],

        schemas: [
          {
            field: 'datetime',
            label: '时间',
            component: 'RangePicker',
            defaultValue: [moment().add(-6, 'day'), new Date()],
            colProps: { span: 12 },
          },
          {
            field: 'status',
            label: '状态',
            component: 'Select',
            componentProps: {
              options: [
                {
                  label: '已处理',
                  value: 2,
                },
                {
                  label: '未处理',
                  value: '1',
                },
              ],
            },
            colProps: { span: 6 },
          },
          // {
          //   field: 'start_time',
          //   label: '时间',
          //   component: 'DatePicker',
          //   show: false,
          // },
          // {
          //   field: 'end_time',
          //   component: 'DatePicker',
          //   label: '时间',
          //   show: false,
          // },
        ],
        showActionButtonGroup: false,
        // actionColOptions: {
        //   flex: 'auto',
        // },
        autoSubmitOnEnter: true,
      });

      const chartRef = ref<HTMLDivElement | null>(null);
      const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>, 'dark');
      let xData: (string | null)[] = [];
      let serData: (number | null)[] = [];

      function updateChart(cData) {
        // xData = [];
        // for (let i = 0; i < 7; i++) {
        //   xData.unshift(moment(nowDate).add(-i, 'day').format('YYYY-MM-DD'));
        // }
        xData = [];
        serData = [];
        cData.forEach((element) => {
          xData.push(element.time);
          serData.push(element.count);
        });
        // xData.push(
        //   moment(nowDate)
        //     .add(-7 + xData.length, 'day')
        //     .format('YYYY-MM-DD'),
        // );
        // serData.push(parseInt(Math.random() * 1000 + 2000));
        setOptions(
          Object.assign({}, chartOptions, {
            xAxis: {
              type: 'category',
              data: xData,
            },
            yAxis: [
              {
                // gridIndex: 0,
                // interval: 1,
                min: 0,
                axisTick: { show: false },
                axisLabel: { show: true },
                splitLine: { show: true },
                // axisLine: { show: true, lineStyle: { color: '#6173a3' } },
              },
            ],
            // tooltip: {
            //   formatter: (params) => {
            //     console.log(params);
            //   },
            // },
            series: [
              {
                data: serData,
                type: 'bar',
                width: 12,
                name: '数量',
                xAxisIndex: 0,
                yAxisIndex: 0,
                barWidth: '45%',
                itemStyle: { color: '#86c9f4' },
                label: { show: true, position: 'right', color: '#9EA7C4' },
              },
            ],
          }),
        );
      }

      async function handleSubmit() {
        const data = await validate();
        console.log(data);

        console.log(getFieldsValue());
        const times = getFieldsValue();
        times.start_time = moment(times.start_time * 1000)
          .startOf('day')
          .unix();
        times.end_time = moment(times.end_time * 1000)
          .endOf('day')
          .unix();
        getCountData(times);
        // page.value = 1;
        // await fetch(data);
      }

      function getCountData(times) {
        let diffDay = moment(times.end_time * 1000).diff(moment(times.start_time * 1000), 'day');
        let diffMonth = moment(times.end_time * 1000).diff(
          moment(times.start_time * 1000),
          'month',
        );
        let diffYear = moment(times.end_time * 1000).diff(moment(times.start_time * 1000), 'year');
        let type = 1;
        if (diffYear > 1) {
          type = 3;
        } else if (diffYear === 1) {
          if (diffMonth < 12) {
            if (diffDay < 30) {
              type = 1;
            } else {
              type = 2;
            }
          } else {
            type = 3;
          }
        } else {
          if (diffDay > 30) {
            type = 2;
          } else {
            type = 1;
          }
        }
        getPatrolCount({ ...times, type }).then((res) => {
          console.log(res);
          updateChart(res);
        });
      }

      onMounted(() => {
        setOptions(chartOptions);
        setTimeout(() => {
          handleSubmit();
        }, 500);
      });

      return {
        registerForm,
        handleSubmit,
        chartRef,
      };
    },
  });
</script>
